//
//  NSString+YTAdd.m
//  tesDemo02
//
//  Created by 拓客营 on 2022/3/21.
//

#import <CommonCrypto/CommonCryptor.h>
#import "NSString+YTAdd.h"
#import <CommonCrypto/CommonDigest.h>
#define     LocalStr_None           @""
static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@implementation NSString (YTAdd)

// 判断是否是中文
- (BOOL)isChinese
{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}

//字符串判断是否为空
- (BOOL)isEmpty {

    if (self == nil || self == NULL) {
        return YES;
    }
    if ([self isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        return YES;
    }
    if (self.length == 0) {
        return YES;
    }
    return NO;
}

// 计算文本高度
+(CGFloat)heightOfString:(NSString *)string font:(UIFont *)font width:(CGFloat)width
{
    CGRect bounds;
    NSDictionary * parameterDict=[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    bounds=[string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:parameterDict context:nil];
    return bounds.size.height;
}

/// 根据高度度求宽度
/// @param text     计算的内容
/// @param height   计算的高度
/// @param font     字体大小
+ (CGFloat)getWidthWithText:(NSString *)text height:(CGFloat)height font:(CGFloat)font {
    
    if (text == nil || [text isEqualToString:@""]) {
        text = @"无";
    }
    if (font <= 0) {
        font = 13;
    }
    if (height < 0) {
        height = 0;
    }

    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                     context:nil];
//    NSLog(@"%@ 的宽度为：%lf",text,rect.size.width);
    return rect.size.width;
}

// 去除html字符串中的标签
+(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
        
        html = [html stringByReplacingOccurrencesOfString:@"&nbsp" withString:@"。"];
    }
//    NSString * regEx = @"<([^>]*)>";
//    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
}

// 字典转字符串
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

/**
 *  计算富文本字体高度
 *
 *  @param lineSpeace 行高
 *  @param font       字体
 *  @param width      字体所占宽度
 *
 *  @return 富文本高度
 */
-(CGFloat)getSpaceLabelHeightwithSpeace:(CGFloat)lineSpeace withFont:(UIFont*)font withWidth:(CGFloat)width {
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    //    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    /** 行高 */
    paraStyle.lineSpacing = lineSpeace;
    // NSKernAttributeName字体间距
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@0
                          };
    CGSize size = [self boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

//MARK: Date相关
/// 将当前时间格式化为默认格式的字符串
+ (NSString *)stringFromNowDate {
    return [self stringFromDate:[NSDate date]];
}

/// 将当前日期格式化为指定格式的字符串
/// @param format 格式化
+ (NSString *)stringFromNowDateWithFormat:(NSString *)format {
    return [self stringFromDate:[NSDate date] format:format];
}

/// 将日期格式化为字符串，默认格式yyyy-MM-dd HH:mm:ss
/// @param date 日期
+ (NSString *)stringFromDate:(NSDate *)date {
    return [self stringFromDate:date format:@"yyyy-MM-dd HH:mm:ss"];
}

/// 将日期格式化为指定格式的字符串
/// @param date 日期
/// @param format 格式化
+ (NSString *)stringFromDate:(NSDate *)date format:(NSString *)format {
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = format;
    return [formatter stringFromDate:date];
}

/// 将日期格式化为指定格式的字符串 yyyy-MM-dd
/// @param timeStamp 时间戳
+ (NSString *)stringFromTimeStamp:(NSInteger )timeStamp {
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = @" yyyy/MM/dd";
    return [formatter stringFromDate:date];
}

+ (NSString *)stringFromTimeStamp:(NSInteger )timeStamp format:(NSString *)format {
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = format;
    return [formatter stringFromDate:date];
}

// 获取剩余天
+ (NSString *)getDaysWithTimeStemp:(NSInteger)remainSconds {
    
    NSInteger day = remainSconds/(3600*24);
    return FormatString(@"%02ld", day);
}

// 获取剩余小时
+ (NSString *)getHoursWithTimeStemp:(NSInteger)remainSconds {
    NSInteger hour = remainSconds/3600;
    return FormatString(@"%02ld", hour);
}

// 获取剩余分
+ (NSString *)getMinutesWithTimeStemp:(NSInteger)remainSconds {
    NSInteger min = (remainSconds/60)%60;
    return FormatString(@"%02ld", min);
}

// 获取剩余秒
+ (NSString *)getSecondsWithTimeStemp:(NSInteger)remainSconds {
    NSInteger second = remainSconds%60;
    return FormatString(@"%02ld", second);
}

+ (NSString *)getDayHoursMinsSecondsWithTimeStemp:(NSInteger)remainSconds {
    NSInteger day = remainSconds/(3600*24);
    NSInteger hour = remainSconds/3600%24;
    NSInteger min = (remainSconds/60)%60;
    NSInteger second = remainSconds%60;
    
    NSString *dayStr = FormatString(@"%ld天", day);
    NSString *hourStr = FormatString(@"%ld时", hour);
    NSString *minStr = FormatString(@"%ld分", min);
    NSString *secondStr = FormatString(@"%ld秒", second);
    
    if (day != 0) {
        return FormatString(@"%@%@%@%@",dayStr, hourStr, minStr, secondStr);
    }
    if (hour != 0) {
        return FormatString(@"%@%@%@", hourStr, minStr, secondStr);
    }
    if (minStr != 0) {
        return FormatString(@"%@%@", minStr, secondStr);
    }
    if (secondStr != 0) {
        return FormatString(@"%@", secondStr);
    }
    return @"";
}

+ (NSString *)getSepareDayHoursMinsSecondsWithTimeStemp:(NSInteger)remainSconds {
    NSInteger day = remainSconds/(3600*24);
    NSInteger hour = remainSconds/3600%24;
    NSInteger min = (remainSconds/60)%60;
    NSInteger second = remainSconds%60;
    
    NSString *dayStr = FormatString(@"%02ld", day);
    NSString *hourStr = FormatString(@"%02ld", hour);
    NSString *minStr = FormatString(@"%02ld", min);
    NSString *secondStr = FormatString(@"%02ld", second);
    
    
    return FormatString(@"%@:%@:%@:%@",dayStr, hourStr, minStr, secondStr);;
}

+ (NSString *)getHoursMinsSecondsWithTimeStemp:(NSInteger)remainSconds {

    NSInteger hour = remainSconds/3600;
    NSInteger min = (remainSconds/60)%60;
    NSInteger second = remainSconds%60;
    
    NSString *hourStr = FormatString(@"%02ld", hour);
    NSString *minStr = FormatString(@"%02ld", min);
    NSString *secondStr = FormatString(@"%02ld", second);
    
    
    return FormatString(@"%@:%@:%@", hourStr, minStr, secondStr);
}


//MARK: 正则判断
- (BOOL)isAvailableEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

- (BOOL)isUrl {
    
    if(self == nil) {
        return NO;
    }
    
    NSString *url;
    if (self.length>4 && [[self substringToIndex:4] isEqualToString:@"www."]) {
        url = [NSString stringWithFormat:@"http://%@",self];
    }else{
        url = self;
    }
    NSString *urlRegex = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
    NSPredicate* urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegex];
    return [urlTest evaluateWithObject:url];
}

- (BOOL)valiMobile {
    
    NSString * MOBILE = @"1+[3456789]+\\d{9}";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:self];
}

- (BOOL)isPassWordLegal {
    BOOL result = false;
    if ([self length] >= 6){
        // 判断长度大于6位后再接着判断是否同时包含数字和字符
//        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$";
        NSString * regex = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&.,])[A-Za-z\\d$@$!%*?&.,]{10,}";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:self];
    }
    return result;
}

- (BOOL)isPureInt {
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

// 判断纯数字
- (BOOL)isNumber{
    if (self.length == 0){
        return NO;
    }
    NSString *regex = @"^[0-9]+([.]{0,1}[0-9]+){0,1}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:self];
}
- (BOOL)isPrice {
    
    NSString *stringRegex = @"(([0]|(0[.]\\d{0,2}))|([1-9]\\d{0,8}(([.]\\d{0,2})?)))?";//一般格式 d{0,8} 控制位数
    NSPredicate *money = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stringRegex];
    return  [money evaluateWithObject:self];
}

-(BOOL)isSMSCode {
    if (self.length != 6) {
        return NO;
    }
    if (![self isPureInt]) {
        return NO;
    }
    return YES;
}

//身份证号
-(BOOL)validateIdentityCard{
   BOOL flag;
   if (self.length <= 0) {
        flag = NO;
        return flag;
   }
   NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
   NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
   return [identityCardPredicate evaluateWithObject:self];
}

- (BOOL)JudgeTheillegalCharacter{
    //    //提示 标签不能输入特殊字符
    //    NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    //    NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    //    if (![emailTest evaluateWithObject:content]) {
    //        return YES;
    //    }
    //    return NO;
    NSRange urgentRange = [self rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @"~￥#&*<>《》()[]{}【】^@/￡¤￥|§¨「」『』￠￢￣~@#￥&*（）——+|《》$_€"]];
    if (urgentRange.location == NSNotFound)
    {
        return NO;
    }
    return YES;
}

- (BOOL)stringContainsEmoji{
    __block BOOL returnValue = NO;
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        const unichar hs = [substring characterAtIndex:0];
        // surrogate pair
        if (0xd800 <= hs && hs <= 0xdbff) {
                if (substring.length > 1) {
                        const unichar ls = [substring characterAtIndex:1];
                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                             returnValue = YES;
                        }
                 }
            } else if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 if (ls == 0x20e3) {
                       returnValue = YES;
                 }
             } else {
                  // non surrogate
                  if (0x2100 <= hs && hs <= 0x27ff) {
                        returnValue = YES;
                   } else if (0x2B05 <= hs && hs <= 0x2b07) {
                        returnValue = YES;
                  } else if (0x2934 <= hs && hs <= 0x2935) {
                        returnValue = YES;
                  } else if (0x3297 <= hs && hs <= 0x3299) {
                        returnValue = YES;
                  } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                        returnValue = YES;
             }
         }
    }];
    return returnValue;
}

//MARK: 字符串加密
+ (NSString *)base64EncodeString:(NSString *)string{
    //1、先转换成二进制数据
    NSData *data =[string dataUsingEncoding:NSUTF8StringEncoding];
    //2、对二进制数据进行base64编码，完成后返回字符串
    return [data base64EncodedStringWithOptions:0];
}

+ (NSString *)base64DecodeString:(NSString *)string{
    //注意：该字符串是base64编码后的字符串
    //1、转换为二进制数据（完成了解码的过程）
    NSData *data=[[NSData alloc]initWithBase64EncodedString:string options:0];
    //2、把二进制数据转换成字符串
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}

// 字符串转base64（加密）
+ (NSString *)base64StringFromText:(NSString *)text
{
    if (text && ![text isEqualToString:LocalStr_None]) {
        //取项目的bundleIdentifier作为KEY  改动了此处
        //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
        NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
        //IOS 自带DES加密 Begin  改动了此处
        //data = [self DESEncrypt:data WithKey:key];
        //IOS 自带DES加密 End
        return [self base64EncodedStringFrom:data];
    }
    else {
        return LocalStr_None;
    }
}

// base64转字符串（解密）
+ (NSString *)textFromBase64String:(NSString *)base64
{
    if (base64 && ![base64 isEqualToString:LocalStr_None]) {
        //取项目的bundleIdentifier作为KEY   改动了此处
        //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
        NSData *data = [self dataWithBase64EncodedString:base64];
        //IOS 自带DES解密 Begin    改动了此处
        //data = [self DESDecrypt:data WithKey:key];
        //IOS 自带DES加密 End
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    else {
        return LocalStr_None;
    }
}

/******************************************************************************
 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
 函数描述 : 文本数据进行DES加密
 输入参数 : (NSData *)data
 (NSString *)key
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 : 此函数不可用于过长文本
 ******************************************************************************/
+ (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeDES,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    
    free(buffer);
    return nil;
}

/******************************************************************************
 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
 函数描述 : 文本数据进行DES解密
 输入参数 : (NSData *)data
 (NSString *)key
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 : 此函数不可用于过长文本
 ******************************************************************************/
+ (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeDES,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    
    free(buffer);
    return nil;
}

/******************************************************************************
 函数名称 : + (NSData *)dataWithBase64EncodedString:(NSString *)string
 函数描述 : base64格式字符串转换为文本数据
 输入参数 : (NSString *)string
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 :
 ******************************************************************************/
+ (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    if (string == nil)
        [NSException raise:NSInvalidArgumentException format:nil];
    if ([string length] == 0)
        return [NSData data];
    
    static char *decodingTable = NULL;
    if (decodingTable == NULL)
    {
        decodingTable = malloc(256);
        if (decodingTable == NULL)
            return nil;
        memset(decodingTable, CHAR_MAX, 256);
        NSUInteger i;
        for (i = 0; i < 64; i++)
            decodingTable[(short)encodingTable[i]] = i;
    }
    
    const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
    if (characters == NULL)     //  Not an ASCII string!
        return nil;
    char *bytes = malloc((([string length] + 3) / 4) * 3);
    if (bytes == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (YES)
    {
        char buffer[4];
        short bufferLength;
        for (bufferLength = 0; bufferLength < 4; i++)
        {
            if (characters[i] == '\0')
                break;
            if (isspace(characters[i]) || characters[i] == '=')
                continue;
            buffer[bufferLength] = decodingTable[(short)characters[i]];
            if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!
            {
                free(bytes);
                return nil;
            }
        }
        
        if (bufferLength == 0)
            break;
        if (bufferLength == 1)      //  At least two characters are needed to produce one byte!
        {
            free(bytes);
            return nil;
        }
        
        //  Decode the characters in the buffer to bytes.
        bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
        if (bufferLength > 2)
            bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
        if (bufferLength > 3)
            bytes[length++] = (buffer[2] << 6) | buffer[3];
    }
    
    bytes = realloc(bytes, length);
    return [NSData dataWithBytesNoCopy:bytes length:length];
}

/******************************************************************************
 函数名称 : + (NSString *)base64EncodedStringFrom:(NSData *)data
 函数描述 : 文本数据转换为base64格式字符串
 输入参数 : (NSData *)data
 输出参数 : N/A
 返回参数 : (NSString *)
 备注信息 :
 ******************************************************************************/
+ (NSString *)base64EncodedStringFrom:(NSData *)data
{
    if ([data length] == 0)
        return @"";
    
    char *characters = malloc((([data length] + 2) / 3) * 4);
    if (characters == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (i < [data length])
    {
        char buffer[3] = {0,0,0};
        short bufferLength = 0;
        while (bufferLength < 3 && i < [data length])
            buffer[bufferLength++] = ((char *)[data bytes])[i++];
        
        //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
        characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
        characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        if (bufferLength > 1)
            characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        else characters[length++] = '=';
        if (bufferLength > 2)
            characters[length++] = encodingTable[buffer[2] & 0x3F];
        else characters[length++] = '=';
    }
    
    return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
}

//MARK: --------------------转为NSData--------------------
-(NSData *)toData {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}


//将字典转换成json格式字符串,不含 这些符号

+ (NSString *)jsonStringCompactFormatForDictionary:(NSDictionary *)dicJson {
    
    if (![dicJson isKindOfClass:[NSDictionary class]] || ![NSJSONSerialization isValidJSONObject:dicJson]) {
        
        return nil;

    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJson options:0 error:nil];

    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    return strJson;

}

//将数组转换成json格式字符串,不含 这些符号

+ (NSString *)jsonStringCompactFormatForNSArray:(NSArray *)arrJson {

    if (![arrJson isKindOfClass:[NSArray class]] || ![NSJSONSerialization isValidJSONObject:arrJson]) {

        return nil;

    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrJson options:0 error:nil];

    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    return strJson;

}

//将字典转换成json格式字符串,含 这些符号,便于阅读

+ (NSString *)jsonStringPrettyPrintedFormatForDictionary:(NSDictionary *)dicJson {

    if (![dicJson isKindOfClass:[NSDictionary class]] || ![NSJSONSerialization isValidJSONObject:dicJson]) {

        return nil;

    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJson options:NSJSONWritingPrettyPrinted error:nil];

    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    return strJson;

}

//MARK: --------------------通过时间戳生成UUID--------------------
+(NSString *)uuid {
    char data[10];
    for (int x=0;x<10;data[x++] = (char)('A' + (arc4random_uniform(26))));
    
    NSDate *  datenow=[NSDate date];
    
    NSString *ns_sendCount = [[NSUserDefaults standardUserDefaults] objectForKey:@"sendMessageCount"];
    int sendCount = [ns_sendCount intValue];
    NSDate *preSendTime = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"preSendTime"];
    
    if (preSendTime == nil){
        [[NSUserDefaults standardUserDefaults] setObject:datenow forKey:@"preSendTime"];
    }else{
//        NSCalendar *chineseClendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar];
        
        NSCalendar *chineseClendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        
        NSUInteger unitFlags =  NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitDay| NSCalendarUnitMonth | NSCalendarUnitYear;
        
        NSDateComponents *DateComponent = [chineseClendar components:unitFlags fromDate:preSendTime toDate:datenow options:0];
        
        if ([DateComponent day] > 0){
            [[NSUserDefaults standardUserDefaults] setObject:datenow forKey:@"preSendTime"];
            [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"sendMessageCount"];
            sendCount = 0;
        }else{
            sendCount ++;
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d",sendCount] forKey:@"sendMessageCount"];
        }
    }
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    NSString * n_str = [NSString stringWithFormat:@"%@%@%@%@%@",
                        [[NSString alloc] initWithBytes:data length:10 encoding:NSUTF8StringEncoding]
                        ,@"-"
                        ,timeSp
                        ,@"-"
                        ,[NSString stringWithFormat:@"%d",sendCount]];
    
    return n_str;
}

+(NSString *)configSendTimeFormatter:(NSString *)timeStamp {
    
    NSInteger seconds = [timeStamp integerValue];
    NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:seconds];
     
    NSCalendar *calendar = [ NSCalendar currentCalendar ];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear ;
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[ NSDate date ]];
    NSDateComponents *myCmps = [calendar components:unit fromDate:myDate];
     
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc ] init ];
     
    //2. 指定日历对象,要去取日期对象的那些部分.
//    NSDateComponents *comp =  [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:myDate];
     
    if (nowCmps.year != myCmps.year || nowCmps.month != myCmps.month) {
        dateFmt.dateFormat = @"yyyy-MM-dd HH:mm";
    } else {
        if (nowCmps.day == myCmps.day) {
//            dateFmt.AMSymbol = @"上午";
//            dateFmt.PMSymbol = @"下午";
            dateFmt.dateFormat = @"HH:mm";
 
        } else {
            dateFmt.dateFormat = @"MM-dd HH:mm";
        }
    }
    return [dateFmt stringFromDate:myDate];
}

// 金额处理
+(NSString *)configToMoneyString:(NSString *)oldPrice{
    NSString *MM = @"";
    if ([oldPrice containsString:@"."]) {
        NSArray *array_XString = [oldPrice componentsSeparatedByString:@"."];
        NSString *string_XLast = array_XString.lastObject;
        if (string_XLast.length == 1 ) {
            MM = [NSString stringWithFormat:@"%.1f",[oldPrice floatValue]];
        }else if (string_XLast.length >=2){
            MM = [NSString stringWithFormat:@"%.2f",[oldPrice floatValue]];
        }
        if (string_XLast.length >=2){
            if ([MM hasSuffix:@"00"]) {
                MM = [NSString stringWithFormat:@"%.0f" , [MM floatValue]];
            }else if ([MM hasSuffix:@"0"]){
                MM = [NSString stringWithFormat:@"%.1f" , [MM floatValue]];
            }
        }else if (string_XLast.length ==1 ){
            if ([MM hasSuffix:@"0"]) {
                MM =[NSString stringWithFormat:@"%.0f" , [MM floatValue]];
            }
        }
    }else{
        MM =oldPrice;
    }
    if ([MM hasSuffix:@".00"]) {
        MM = [NSString stringWithFormat:@"%.0f",[MM floatValue]];
    }
    return MM;
}

// 金额处理 四舍五入后，再处理金额
+(NSString *)configToMoneyDecimalNumber:(NSDecimalNumber *)oldPrice {
//    NSDecimalNumber *resultNum = [NSDecimalNumber decimalNumberWithString:oldPrice];
    NSDecimalNumberHandler *roundBankers = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
    NSDecimalNumber *result = [oldPrice decimalNumberByAdding:[NSDecimalNumber decimalNumberWithString:@"0"] withBehavior:roundBankers];
    return [self configToMoneyString:[NSString stringWithFormat:@"%f",result.floatValue]];
}

// html 字符串处理
+ (NSString *)htmlEntityDecode:(NSString *)string{
    //将特殊字符替换了

    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];

    // 图片自适应
    string = [NSString stringWithFormat:@"<html> \n"
              "<head> \n"
              "<style type=\"text/css\"> \n"
              "</style> \n"
              "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">"
              "</head> \n"
              "<body>"
              "<script type='text/javascript'>"
              "window.onload = function(){\n"
              "var $img = document.getElementsByTagName('img');\n"
              "for(var p in  $img){\n"
              "p=Number(p);\n"
//              "$img[p].style.width = '100%%';\n"
//              "$img[p].style.height ='auto'\n"
              "}\n"
              "}"
              "</script>%@"
              "</body>"
              "</html>",string];
    return string;
}

+(NSString *)hMacMD5String:(NSString *)string Key:(NSString *)keyStr
{
    const char *cKey  = [keyStr cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [string cStringUsingEncoding:NSUTF8StringEncoding];
    const unsigned int blockSize = 64;
    char ipad[blockSize];
    char opad[blockSize];
    char keypad[blockSize];
    
    unsigned int keyLen = (unsigned int)strlen(cKey);
    CC_MD5_CTX ctxt;
    if (keyLen > blockSize) {
        CC_MD5_Init(&ctxt);
        CC_MD5_Update(&ctxt, cKey, keyLen);
        CC_MD5_Final((unsigned char *)keypad, &ctxt);
        keyLen = CC_MD5_DIGEST_LENGTH;
    }
    else {
        memcpy(keypad, cKey, keyLen);
    }
    
    memset(ipad, 0x36, blockSize);
    memset(opad, 0x5c, blockSize);
    
    int i;
    for (i = 0; i < keyLen; i++) {
        ipad[i] ^= keypad[i];
        opad[i] ^= keypad[i];
    }
    
    CC_MD5_Init(&ctxt);
    CC_MD5_Update(&ctxt, ipad, blockSize);
    CC_MD5_Update(&ctxt, cData, (CC_LONG)strlen(cData));
    unsigned char md5[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(md5, &ctxt);
    
    CC_MD5_Init(&ctxt);
    CC_MD5_Update(&ctxt, opad, blockSize);
    CC_MD5_Update(&ctxt, md5, CC_MD5_DIGEST_LENGTH);
    CC_MD5_Final(md5, &ctxt);
    
    const unsigned int hex_len = CC_MD5_DIGEST_LENGTH*2+2;
    char hex[hex_len];
    for(i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
          //小写加密改为小写字母x
        snprintf(&hex[i*2], hex_len-i*2, "%02X", md5[i]);
    }
    
    NSData *HMAC = [[NSData alloc] initWithBytes:hex length:strlen(hex)];
    NSString *hash = [[NSString alloc] initWithData:HMAC encoding:NSUTF8StringEncoding];
    return hash;
}

+ (NSString *)convertToJsonData:(NSDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

@end
